import { ISubscriber, IVMMain, IWatcher } from "../Interfaces/IMVVM";
import { IDispose } from "../Interfaces/IGameManager";

/**订阅器 */
export class Subscriber implements ISubscriber, IDispose {
  //订阅编号
  static uid: number = 1;
  //当前订阅编号
  id: number;
  //订阅监听 数据集合
  subs: IWatcher[] = [];
  isChild: boolean = false;
  private vm: IVMMain;
  constructor(that: IVMMain) {
    this.vm = that;
    this.id = Subscriber.uid++;
    this.vm.$pools.push(this);
  }
  /**
   * 添加订阅
   * @param sub 订阅者
   */
  add(sub: IWatcher) {
    this.subs.push(sub);
  }
  /**
   * 移除订阅
   * @param sub 订阅者
   */
  remove(sub: IWatcher) {
    let index = this.subs.indexOf(sub);
    if (index !== -1) {
      this.subs.splice(index, 1);
    }
  }
  /**
   * 数据变更通知
   */
  notify() {
    if (!this.subs) return;
    this.subs.forEach((sub) => {
      sub.update();
    });
  }

  /**
   * 添加依赖监听
   */
  depend() {
    if (this.vm.$targetWatcher) this.vm.$targetWatcher.addSub(this);
  }
  dispose(disposing?: boolean) {}
}
